package logic

import (
	"context"
	"fmt"
	"yzy5.21wrk/Models"

	"yzy5.21wrk/user_srv/internal/svc"
	"yzy5.21wrk/user_srv/user_srv"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginRestLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginRestLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginRestLogic {
	return &LoginRestLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginRestLogic) LoginRest(in *user_srv.Login_RestRequest) (*user_srv.Login_RestResponse, error) {
	// todo: add your logic here and delete this line
	var user Models.User
	key := fmt.Sprintf("%s", in.Phone)
	get, _ := Models.RDB.Get(Models.Ctx, key).Result()
	if get != in.Code {
		return nil, fmt.Errorf("验证码错误")
	}
	if Models.DB.Where("phone = ?", in.Phone).Find(&user).Limit(1).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	if user.ID == 0 {
		user = Models.User{
			Phone: in.Phone,
			Name:  in.Phone + "用户",
		}
		if Models.DB.Create(&user).Error != nil {
			return nil, fmt.Errorf("服务器繁忙")
		}
		if Models.DB.Where("phone = ?", in.Phone).Limit(1).Find(&user).Error != nil {
			return nil, fmt.Errorf("服务器繁忙")
		}
	}
	return &user_srv.Login_RestResponse{
		Id: int64(user.ID),
	}, nil
}
